import Flock from "./flock"
import Target from "./target"

import Grid from "./grid"
import Grid2 from "./grid2"
import echarts from "echarts"
import MRG32k3a from "../common/utils/MRG32k3a"
import Monitor from "./monitor"


// 模拟器总体设计
let simulation = {};  // 定义模拟器对象
simulation.canvas = null;  // 传递canvas对象作为全局对象
simulation.flock = null;  // 定义集群类
simulation.debug = true;  // 是否开启调试模式
simulation.width = null;  // 模拟器高度
simulation.height = null;  // 模拟器高度
simulation.monitor = null;  // 模拟器监控


// 干扰物定义 fixme 这个受到html参数控制
simulation.inter_range = 170;  // 干扰物范围170/510
simulation.inter_num = 9;  // 干扰物个数9/1

// 搜索情况
simulation.gridSize = [800, 800];  // 区域分解网格数量
simulation.targetDistribCells = simulation.gridSize[0] * simulation.gridSize[1];
simulation.targetNum = 2;  // fixme 不用在这里设置目标数量
simulation.iteration_sum = 2000;  // 总迭代次数,fixme 不用在这里控制迭代次数
simulation.iteration = 0;  // 当前迭代次数
simulation.lastEvaluation = 0;  // 最新的评价值

simulation.setup = function () {
    // 获取调试模式选择的值
    let debug = $("#debug").val();
    if (debug === "none") {
        simulation.debug = false;
    } else {
        simulation.debug = true;
    }

    // 获取协同搜索算法
    let method = $("#method").val();
    if (method === "greedy") {
        simulation.UAVs_strategy = "贪心算法";
    } else if (method === "cmeans") {
        simulation.UAVs_strategy = "C均值算法";
    } else if (method === "dynamic") {
        simulation.UAVs_strategy = "连通域动态算法";
    }

    // 获取显示方式的值
    simulation.isDrawReturn = $("#showReturn").is(':checked');  // 是否在每个格子右上角绘制回报率
    simulation.isDrawConnectCell = $("#showZero").is(':checked');  // 是否绘制return为0的联通格子
    simulation.isDrawCluster = $("#showCluster").is(':checked');  // 绘制聚类情况
    simulation.isDrawTree = $("#showTree").is(':checked');  // 是否绘制树形结构

    // 改变主题模式
    simulation.draw_style = $("#theme").val();  // 绘图风格，有“dark”和“white"两种
    if (simulation.draw_style === "white") {
        $("#main").css("background-color", "#CCC");
    } else {
        $("#main").css("background-color", "#132c3d");
    }

    // 网格数量设置
    let gridSize = $("#gridSize").val();
    if (gridSize === "") {
        gridSize = 10;
    }
    gridSize = parseInt(gridSize);
    simulation.gridSize = [gridSize, gridSize];
    simulation.targetDistribCells = simulation.gridSize[0] * simulation.gridSize[1];

    // 目标数量设置
    let targetNum = $("#targetNum").val();
    if (targetNum === "") {
        targetNum = 6;
    }
    simulation.targetNum = parseInt(targetNum);

    // 聚类个数设置
    let clusterNum = $("#clusterNum").val();
    if (clusterNum === "") {
        clusterNum = 5;
    }
    simulation.clusterNum = parseInt(clusterNum);
};

// 重新生成目标分布
simulation.targetRebuild = function () {
    simulation.flock.add_all_targets();
};


// 开始或者暂停
simulation.pauseOrRun = function () {
    let startBtn = document.getElementById("start_btn");
    if (startBtn.innerText === "开始计算") {
        simulation.flock.run = true;
        startBtn.innerText = "暂停计算";
    }
    else if (startBtn.innerText === "暂停计算") {
        simulation.flock.run = false;
        startBtn.innerText = "继续计算"
    } else if (startBtn.innerText === "继续计算") {
        simulation.flock.run = true;
        startBtn.innerText = "暂停计算";
    }
};

// 拷贝速度历史
simulation.copyVelHistory = function () {
    let $copybtn = $("#copyVelBtn");
    let info = "";

    for (let i = 0; i < simulation.flock.leaders.length; i++) {
        let leader = simulation.flock.leaders[i];
        info += leader.leaderName;
        info += leader.velHistory.toString() + "\n";
    }
    $copybtn.attr("data-clipboard-text", info);
    // 实例化剪贴板对象
    let clipboard = new Clipboard("#copyVelBtn");
    // 显示"复制成功"的信息框
    $("#copy_message").show(300);
    setTimeout(function () {
        $("#copy_message").hide(300);
    }, 1500);
};

// 拷贝位置历史
simulation.copyPosHistory = function () {
    let $copybtn = $("#copyPosBtn");
    let info = "";

    for (let i = 0; i < simulation.flock.leaders.length; i++) {
        let leader = simulation.flock.leaders[i];
        info += leader.leaderName;
        info += leader.posHistory.toString() + "\n";
    }
    $copybtn.attr("data-clipboard-text", info);
    let clipboard = new Clipboard("#copyPosBtn");  // 实例化剪贴板对象
    $("#copy_message").show(300);
    setTimeout(function () {
        $("#copy_message").hide(300);
    }, 1500);
};

// 拷贝回报率
simulation.copyEvalution = function () {
    let $copybtn = $("#copyReturnBtn");
    let info = "";
    for (let i = 0; i < simulation.flock.evaluation.length; i++) {
        let evaluation = simulation.flock.evaluation[i].toFixed(7);
        info += evaluation + "\n";
    }
    $copybtn.attr("data-clipboard-text", info);
    let clipboard = new Clipboard("#copyReturnBtn");  // 实例化剪贴板对象
    $("#copy_message").show(300);
    setTimeout(function () {
        $("#copy_message").hide(300);
    }, 1500);
};


// 全局数据更新方法
simulation.update = function () {
    if (simulation.flock.run) {
        simulation.flock.update();
    }
    simulation.redraw();
};

// 重新绘制所有对象
simulation.redraw = function () {
    let ctx = simulation.canvas.getContext("2d");
    ctx.clearRect(0, 0, simulation.canvas.width, simulation.canvas.height);  // 清空绘制区域
    ctx.fillStyle = "#f6f6f6";
    ctx.strokeStyle = "#aecbf6";
    simulation.flock.draw(ctx, simulation.canvas.width, simulation.canvas.height);  // 绘制
};

// 在canvas中增加对象
simulation.addObject = function (evt) {
    let canvas = simulation.canvas;
    // 获得鼠标点击位置
    let pos = get_canvas_pos(canvas, evt);
    let x = pos.x;
    let y = pos.y;
    // 如果点击的位置在canvas之外,则无效果
    if (y <= 1 || x > canvas.width || y > canvas.height)
        return;
    let target = new Target(x, y);
    simulation.flock.addTarget(target);

    // let target2 = new Target2(canvas);
    // simulation.flock.addTarget(target2);

    //获取鼠标在canvas上的坐标
    function get_canvas_pos(canvas, e) {
        let rect = canvas.getBoundingClientRect();
        let leftB = parseInt(document.defaultView.getComputedStyle(canvas).borderLeftWidth);//获取的是样式，需要转换为数值
        let topB = parseInt(document.defaultView.getComputedStyle(canvas).borderTopWidth);
        return {
            x: (e.clientX - rect.left) - leftB,
            y: (e.clientY - rect.top) - topB
        };
    }
};

// 自适应屏幕并且重绘
simulation.adjustAndRedraw = function () {
    simulation.canvas.width = window.innerHeight-137;
    simulation.canvas.height = window.innerHeight - 137;
    simulation.redraw();
};


// 模拟器初始化
simulation.init = function () {
    let canvas = document.getElementById("main");
    // 将canvas作为simulation的全局变量
    simulation.canvas = canvas;
    // 设置canvas大小为正方形
    simulation.canvas.width = window.innerHeight-137;
    simulation.canvas.height = window.innerHeight - 137;
    // 生成新的随机seed
    simulation.prng = new MRG32k3a();
    // 新建种群类
    simulation.flock = new Flock(simulation.canvas, simulation.iteration_sum, simulation.targetNum);
    // 给全局增加改变大小的事件，使得canvas大小自适应
    window.addEventListener("resize", simulation.adjustAndRedraw, false);
    // 给canvas内增加点击事件
    simulation.canvas.addEventListener("click", simulation.addObject, false);
    // 初始化网格
    //simulation.flock.addGrid(new Grid(canvas, simulation.gridSize, simulation.targetNum));  // 绘制网格
    //simulation.flock.addGrid2(new Grid2(canvas, [8, 8], simulation.targetNum));  // 绘制中心区网格
    // 从储存中增加目标
    simulation.flock.add_targets_from_store();
    // 绘制canvas
    simulation.redraw();
    // 每秒30帧
    let fps = 30;
    setTimeout(()=>{
        simulation.flock.run = true
    }, 5000)
    // 每隔一定时间执行update方法
    window.setInterval(simulation.update, 1000 / fps);
};

export default simulation;

window.onload = simulation.init;  // 开始方法